import { FC, useEffect, useMemo, useRef, useState } from 'react';
// import SparkMD5 from "spark-md5";
import { CloseOutlined, MinusOutlined } from '@ant-design/icons';
import { motion } from 'framer-motion';
import { css } from '@emotion/css';
import { Button, Input } from 'antd';
interface IUploadBox {
  uploadModal: boolean;
  setUploadModal(val: boolean): void;
}

const oldhidden = {
  opacity: 0,
  top: 49,
  left: 209,
  width: 75,
  height: 32,
  zIndex: -1,
  border: '1px solid #333',
  borderRadius: '8px',
};
const visible = {
  opacity: 1,
  top: '50%',
  left: '50%',
  width: 600,
  height: 540,
  zIndex: 9,
  border: '1px solid #333',
  borderRadius: '8px',
  transform: 'translate(-50%, -50%)',
};

const animateMap = {
  hidden: {
    opacity: 0,
    top: 49,
    left: 209,
    width: 40,
    height: 14,
    zIndex: -1,
    border: '1px solid #333',
    borderRadius: '8px',
  },
  visible: {
    opacity: 1,
    top: '50%',
    left: '50%',
    width: 600,
    height: 540,
    zIndex: 9,
    border: '1px solid #333',
    borderRadius: '8px',
    transform: 'translate(-50%, -50%)',
    padding: '10px 20px',
  },
  min: {
    opacity: 1,
    top: 49,
    left: 1100,
    width: 110,
    height: 24,
    zIndex: 9,
    border: '1px solid #333',
    borderRadius: '8px',
    transform: 'translate(-50%, -50%)',
    padding: '10px',
  },
};

// a41c1f4399df0734e1ef5dbb7599d576
// const getFileMd5 = (file: File) => {
//   // console.log("file", file.size / 1024 / 1024);
//   return new Promise((resolve) => {
//     const blobSlice = File.prototype.slice
//     // File.prototype.slice ||
//     // File.prototype.mozSlice ||
//     // File.prototype.webkitSlice;
//     const chunkSize = 1024 * 1024 * 25;
//     const chunks = Math.ceil(file.size / chunkSize);
//     let currentChunk = 0;
//     const spark = new SparkMD5.ArrayBuffer();
//     const fileReader = new FileReader();
//     let block;
//     let start = null;
//     let end = null;

//     let blockFileItem: {
//       blockFile: Blob,
//       start: number,
//       end: number,
//       isLastChunk: boolean,
//       hash: string,
//       currentChunk: number,
//       chunkSize: number,
//     }[] = [];

//     fileReader.onload = (e) => {
//       spark.append(e.target?.result as ArrayBuffer);
//       currentChunk++;
//       if (currentChunk < chunks) {
//         loadNext();
//       } else {
//         const md5 = spark.end();
//         // state.current++;
//         resolve({ md5, block: blockFileItem });
//       }
//     };
//     fileReader.onerror = () => {
//       // state.current++;
//       resolve('');
//     };
//     function loadNext() {
//       start = currentChunk * chunkSize;
//       end = start + chunkSize >= file.size ? file.size : start + chunkSize;
//       block = blobSlice.call(file, start, end);
//       fileReader.readAsArrayBuffer(block);
//       let md5Str = `${file.size},${currentChunk}`;
//       blockFileItem.push({
//         blockFile: block,
//         start,
//         end,
//         isLastChunk: start + chunkSize >= file.size,
//         hash: SparkMD5.hash(md5Str),
//         currentChunk,
//         chunkSize,
//       });
//     }
//     // state.blockFile.push(blockFileItem);
//     loadNext();
//   });
// };
const UploadBox: FC<IUploadBox> = ({ uploadModal, setUploadModal }) => {
  const [min, setMin] = useState(false);

  const animate = useMemo(() => {
    console.log('render usemoe', min);
    // 上传窗口开启 并且 最小化关闭 -> 上传窗口开启
    if (uploadModal && !min) {
      return animateMap['visible'];
    }
    // 上传窗口关闭 并且 最小化关闭 -> 全部关闭
    if (!uploadModal && !min) {
      return animateMap['hidden'];
    }

    // 最小化开启 并且 上传窗口开启-> 最小化窗口开启
    if (min && uploadModal) {
      return animateMap['min'];
    }
    // 最小化开启 并且 上传窗口关闭-> 全部关闭
    if (min && !uploadModal) {
      return animateMap['hidden'];
    }
  }, [uploadModal, min]);

  console.log('model box render');

  const handleOk = () => {
    setUploadModal(false);
  };
  // const [hidden, setHidden] = useState(oldhidden)
  const handleCancel = () => {
    setUploadModal(false);
  };
  const handleClickSetMin = () => {
    setMin((oldVal) => !oldVal);
  };

  const handleClickCloseUpload = () => {
    setUploadModal(false);
  };

  const inpntRef = useRef<HTMLInputElement>(null);
  const handleUpload = () => {
    inpntRef.current?.click();
  };
  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files!);
    // 用户没选文件直接取消时 e.target.files Array.from返回为空数组[]
    if (files.length <= 0) return;
    console.log(files);
    // 之后计算md5
    // const data = await Promise.all(files.map(item => getFileMd5(item)))
    // console.log('data', data)
  };

  // const handdleMoseDown = (e: MouseEvent) => {
  //   setHidden((val) => {
  //     return {
  //       ...val,
  //       top: e.pageY,
  //       left: e.pageX,
  //     }
  //   })
  // }
  // useEffect(() => {
  //   document.addEventListener('mousedown', handdleMoseDown)
  //   return () => {
  //     document.removeEventListener('mousedown', handdleMoseDown)
  //   }
  // }, [])
  return (
    <motion.div
      style={{
        position: 'fixed',
        background: '#fff',
      }}
      animate={animate}
    >
      <div
        className={css`
          .title-header {
            display: flex;
            justify-content: space-between;
          }
          .min {
            margin-right: 6px;
          }
          .icon {
            cursor: pointer;
            cursor: pointer;
            padding: 2px;
            border-radius: 2px;
            :hover {
              background: #d9d9d9;
            }
            :active {
              background: #bababa;
            }
          }
          .title {
            cursor: pointer;
            user-select: none;
          }
          .iconbox {
            display: flex;
          }
        `}
      >
        <div className="title-header">
          <div className="title">upload</div>
          <div className="iconbox">
            <MinusOutlined onClick={handleClickSetMin} className="min icon" />
            <CloseOutlined
              onClick={handleClickCloseUpload}
              className="max icon"
            />
          </div>
        </div>
        <div>
          <Button onClick={handleUpload}>上传</Button>
          <input
            ref={inpntRef}
            style={{ display: 'none' }}
            type="file"
            id="filepicker"
            name="fileList"
            multiple
            onChange={handleChange}
          />
        </div>
      </div>
    </motion.div>
  );
};

export default UploadBox;
